/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * MeetRecordController
 * 会议纪要
 * <p>
 * 修改纪录
 * 2020-10-31 版本：1.0 donghang 创建。
 *
 * @version 版本：1.0
 * @author 作者：donghang
 * 创建日期：2020-10-31
 */

package com.topscomm.meet.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.topscomm.base.BaseSystemConst;
import com.topscomm.base.BaseSystemConst.ShareTypeEnum;
import com.topscomm.base.pojo.BasePermissionManageEntity;
import com.topscomm.base.service.IBasePermissionManageService;
import com.topscomm.base.utils.BaseUtils;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboAttachmentEntity;
import com.topscomm.cbo.service.ICboAttachmentService;
import com.topscomm.meet.MeetSystemConst;
import com.topscomm.meet.MeetSystemConst.MeetLauchOrgTypeEnum;
import com.topscomm.meet.MeetSystemConst.MeetOperateTypeEnum;
import com.topscomm.meet.MeetSystemConst.MeetPersonTypeEnum;
import com.topscomm.meet.MeetSystemConst.MeetStateEnum;
import com.topscomm.meet.controller.auto.MeetRecordControllerAuto;
import com.topscomm.meet.pojo.MeetManageEntity;
import com.topscomm.meet.pojo.MeetPersonRecordEntity;
import com.topscomm.meet.pojo.MeetRecordEntity;
import com.topscomm.meet.pojo.MeetTypeManageEntity;
import com.topscomm.meet.service.IMeetManageService;
import com.topscomm.meet.service.IMeetPersonRecordService;
import com.topscomm.meet.service.IMeetTypeManageService;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.constant.TapHttpErrorCode;
import com.topscomm.tap.constant.TapHttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Clob;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: donghang
 * @date: 2020-10-31
 * @description:会议纪要Controller
 * @modify:
 */
@Slf4j
@RestController
@RequestMapping("meet/record")
public class MeetRecordController extends MeetRecordControllerAuto implements IMeetRecordController {
    @Autowired
    private IBasePermissionManageService basePermissionManageService;
    @Autowired
    private IMeetPersonRecordService meetPersonRecordService;
    @Autowired
    private IMeetManageService meetManageService;
    @Autowired
    private IMeetTypeManageService meetTypeManageService;
    @Autowired
    private ICboAttachmentService cboAttachmentService;

    private static final String AttachmentSourceType = "meetRecord";

    /**
     * @param paraMap
     * @return
     * @author: donghang
     * @date: 2020-10-31
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (name like '%{0}%'  or keywords like '%{1}%')", value, value);
        }
        if (paraMap.containsKey("qry_meetnum")) {
            String value = paraMap.get("qry_meetnum").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and meetnum like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_meetid")) {
            String value = paraMap.get("qry_meetid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and meetid = '{0}' ", value);
        }
        if (paraMap.containsKey("qry_begindatetime")) {// 查询的开始时间
            String value = paraMap.get("qry_begindatetime").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and begintime >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddatetime")) {// 查询的结束时间
            String value = paraMap.get("qry_enddatetime").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and begintime <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_meettypeid")) {
            String value = paraMap.get("qry_meettypeid").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and meettypeid = '{0}'", value);
            }
        }
        return sql.toString();
    }

    /**
     * @param paraMap
     * @return
     * @author: donghang
     * @date: 2020-10-31
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    /**
     * 查询
     *
     * @param paraMap
     * @return
     * @description:
     * @author: donghang
     * @date: 2020年11月16日下午3:10:38
     * @modify:
     */
    @Override
    @GetMapping(value = "/list")
    public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle("1=1 ");
            // 组织部门查看的
            String qry_teamid = ConvertUtil.convertToString(paraMap.get("qry_teamid"));
            String qry_deptcode = ConvertUtil.convertToString(paraMap.get("qry_deptcode"));
            if (qry_teamid.length() > 0 && qry_deptcode.length() > 0) {
                sql.appendSingle(
                        " and ((launchorgtype='{0}' and launchorgindex = '{1}') or (launchorgtype='{2}' and launchorgindex like '{3}%'))",
                        MeetLauchOrgTypeEnum.Team, qry_teamid, MeetLauchOrgTypeEnum.Dept, qry_deptcode);
            } else if (qry_teamid.length() > 0) {// 团队
                sql.appendSingle(" and launchorgtype='{0}' and launchorgindex = '{1}'", MeetLauchOrgTypeEnum.Team,
                        qry_teamid);
            } else if (qry_deptcode.length() > 0) {// 部门
                sql.appendSingle(" and launchorgtype='{0}' and launchorgindex like '{1}%'", MeetLauchOrgTypeEnum.Dept,
                        qry_deptcode);
            }
            if (ConvertUtil.convertToString(paraMap.get("qry_typeselect")).equals("all")) {// 查询看所有的
                // 自己管理的
                StringBufferProxy manageSql = new StringBufferProxy();
                String[] manageParams = {"','", "manageusercodes", "','"};
                String[] attendParams = {"','", "attendusercodes", "','"};
                String[] absentParams = {"','", "absentusercodes", "','"};
                manageSql.appendSingle(
                        "  ( select id from meetrecord where usercode = '{0}'  " +
                                " union select id from meetrecord where ({2}) like '%{1}%' " +
                                " union select id from meetrecord where ({3}) like '%{1}%' " +
                                "union select id from meetrecord where ({4}) like '%{1}%') ",
                        this.getUserBean().getUser().getCode(), "," + this.getUserBean().getUser().getCode() + ",",
                        SQLAdapter.concat(manageParams), SQLAdapter.concat(attendParams),
                        SQLAdapter.concat(absentParams), MeetStateEnum.Publish);
                // 配置的可见
                String sqlPermission = this.basePermissionManageService.createUserShareCondition(this.getUserBean(),
                        true, "begintime");
                if (sqlPermission.length() > 0) {
                    StringBufferProxy teamPermissionSql = new StringBufferProxy();
                    teamPermissionSql.appendSingle(
                            "select id from (select meetrecord.id as id, shareobjects,begintime from meetrecord,basepermissionmanage "
                                    + " where  meetrecord.id = basepermissionmanage.sourceid and  basepermissionmanage.sourcetype='{0}' and ({1}) )",
                            MeetRecordEntity.tableName, sqlPermission);
                    sql.appendSingle(" and id in  ({0} union  ({1}) ) and state='{2}'", manageSql.toString(),
                            teamPermissionSql.toString(), MeetStateEnum.Publish);
                } else {
                    sql.appendSingle(" and id in ({0}) and state='{1}'", manageSql.toString(), MeetStateEnum.Publish);
                }
            }
            paraMap.put("sqlwhere", sql.toString());
            paraMap.put("qry_usercode", this.getUserBean().getUser().getCode());
            Query query = new Query(paraMap);
            int totalCount = this.service.getCount1(paraMap, "queryRecordList");
            // 分页拦截处理
            int beginCount = query.getCurrentPage() * query.getPageSize() - query.getPageSize();
            paraMap.put("begincount", beginCount);
            paraMap.put("pagesize", query.getPageSize());
            paraMap.put("IsNeedPage", true);
            List<Map<String, Object>> tempList = null;
            tempList = this.service.queryMap(paraMap, "queryRecordList");
            this.service.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * 重写纪要加载页面
     *
     * @param paraMap
     * @return
     * @description:
     * @author: donghang
     * @date: 2020年9月1日下午4:22:58
     * @modify:
     */
    @Override
    @GetMapping(value = "/load")
    public ResponseResult<Object> load(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String id = ConvertUtil.convertToString(paraMap.get("id"));
            MeetRecordEntity meetRecordEntity = this.service.queryById(id);
            paraMap.put("whereSql", " id in (" + id + ")");
            paraMap.put("qry_usercode", this.getUserBean().getUser().getCode());
            List<Map<String, Object>> dataMapList = this.service.queryMap(paraMap, "queryRecordDetail");
            this.service.setDispFields(dataMapList);
            if (dataMapList.size() == 0) {
                return ResponseResult.error("没有查询到会议资料详情数据");
            }
            Map<String, Object> dataMap = dataMapList.get(0);
            afterLoad(dataMap);
            setAccess(paraMap, dataMap);
            return ResponseResult.ok(dataMap);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @param paraMap
     * @param dataMap
     * @description: 设置纪要和录音的访问权限
     * @author: wanghongwei
     * @date: 2020-11-24 10:49:43
     * @modify:
     */
    private void setAccess(Map<String, Object> paraMap, Map<String, Object> dataMap) {
        // 如果是查询页面,并且记录创建者非当前登录用户，则需要添加权限
        if (MeetSystemConst.MeetTaskSourceType.MeetSearch
                .equals(ConvertUtil.convertToString(paraMap.get("operatetype")))
                && (!ConvertUtil.convertToString(dataMap.get("usercode"))
                .equals(this.getUserBean().getUser().getCode()))) {
            dataMap.put(MeetPersonTypeEnum.Record, false);
            dataMap.put(MeetPersonTypeEnum.Audio, false);
            // 纪要文件是否可看
            String sqlWhere = this.basePermissionManageService.createUserShareCondition(this.getUserBean(), true,
                    "begintime");
            StringBufferProxy sql = new StringBufferProxy();
            if (sqlWhere.length() > 0) {
                sql.appendSingle(" sourcetype='{0}' and sourceid ='{1}' and sourceflag='{2}' and ({3}) ",
                        MeetRecordEntity.tableName, ConvertUtil.convertToString(dataMap.get(MeetRecordEntity.FieldId)),
                        MeetPersonTypeEnum.Record, sqlWhere);
            }
            if (this.service.queryMapByWhere(sql.toString(), "queryPermissionList").size() != 0) {
                dataMap.put(MeetPersonTypeEnum.Record, true);
            }
            // 录音文件是否可看
            sqlWhere = this.basePermissionManageService.createUserShareCondition(this.getUserBean(), true, "begintime");
            sql.clear();
            if (sqlWhere.length() > 0) {
                sql.appendSingle(" sourcetype='{0}' and sourceid ='{1}' and sourceflag='{2}' and ({3}) ",
                        MeetRecordEntity.tableName, ConvertUtil.convertToString(dataMap.get(MeetRecordEntity.FieldId)),
                        MeetPersonTypeEnum.Audio, sqlWhere);
            }
            if (this.service.queryMapByWhere(sql.toString(), "queryPermissionList").size() != 0) {
                dataMap.put(MeetPersonTypeEnum.Audio, true);
            }
            // 属于参会人员或缺席人员可以查看录音或纪要
            String attendUsers = "";
            if (!(dataMap.get(MeetRecordEntity.FieldAttendusercodes) instanceof String)) {
                attendUsers = "," + BaseUtils.ClobToString((Clob) dataMap.get(MeetRecordEntity.FieldAttendusercodes))
                        + ",";
            } else {
                attendUsers = "," + ConvertUtil.convertToString(dataMap.get(MeetRecordEntity.FieldAttendusercodes)) + ",";
            }
            String absentUsers = "";
            if (!(dataMap.get(MeetRecordEntity.FieldAbsentusercodes) instanceof String)) {
                absentUsers = "," + BaseUtils.ClobToString((Clob) dataMap.get(MeetRecordEntity.FieldAbsentusercodes))
                        + ",";
            } else {
                absentUsers = "," + ConvertUtil.convertToString(dataMap.get(MeetRecordEntity.FieldAbsentusercodes)) + ",";
            }
            if (attendUsers.contains("," + this.getUserBean().getUser().getCode() + ",")
                    || absentUsers.contains("," + this.getUserBean().getUser().getCode() + ",")) {
                dataMap.put(MeetPersonTypeEnum.Record, true);
                dataMap.put(MeetPersonTypeEnum.Audio, true);
            }
        } else {
            dataMap.put(MeetPersonTypeEnum.Record, true);
            dataMap.put(MeetPersonTypeEnum.Audio, true);
        }
    }

    /**
     * 参会人，缺席人从会议转过来
     *
     * @param paraMap
     * @description:
     * @author: donghang
     * @date: 2020年11月4日上午9:01:41
     * @modify:
     */
    @Override
    protected void afterLoad(Map<String, Object> paraMap) {
        if (ConvertUtil.convertToString(paraMap.get("meetid")).length() > 0
                && !ConvertUtil.convertToString(paraMap.get("state")).equals(MeetStateEnum.Publish)) {// 纪要从会议转过来，则要查询会议签到记录
            // 没有参会人，则取得会议里面参会人
            if (ConvertUtil.convertToString(paraMap.get(MeetRecordEntity.FieldAttendusercodes)).length() == 0
                    && ConvertUtil.convertToString(paraMap.get(MeetRecordEntity.FieldAbsentusercodes)).length() == 0) {
                List<Map<String, Object>> attendUserList = this.meetPersonRecordService.queryUserRecord(
                        ConvertUtil.convertToString(paraMap.get("meetid").toString()), MeetOperateTypeEnum.YesSign);
                // 参会人
                String attendUserCodes = "", attendUserNames = "";
                for (Map<String, Object> attendMap : attendUserList) {
                    attendUserCodes += attendMap.get(MeetPersonRecordEntity.FieldUsercode) + ",";
                    attendUserNames += attendMap.get(MeetPersonRecordEntity.FieldUsername) + ",";
                }
                if (attendUserCodes.length() > 0) {
                    attendUserCodes = attendUserCodes.substring(0, attendUserCodes.length() - 1);
                    attendUserNames = attendUserNames.substring(0, attendUserNames.length() - 1);
                }
                paraMap.put(MeetRecordEntity.FieldAttendusercodes, attendUserCodes);
                paraMap.put(MeetRecordEntity.FieldAttendusernames, attendUserNames);
                // 缺席人
                List<Map<String, Object>> absentUserList = this.meetPersonRecordService.queryUserRecord(
                        ConvertUtil.convertToString(paraMap.get("meetid").toString()), MeetOperateTypeEnum.NoSign);
                String absentUserCodes = "", absentUserNames = "";
                for (Map<String, Object> attendMap : absentUserList) {
                    absentUserCodes += attendMap.get(MeetPersonRecordEntity.FieldUsercode) + ",";
                    absentUserNames += attendMap.get(MeetPersonRecordEntity.FieldUsername) + ",";
                }
                if (absentUserCodes.length() > 0) {
                    absentUserCodes = absentUserCodes.substring(0, absentUserCodes.length() - 1);
                    absentUserNames = absentUserNames.substring(0, absentUserNames.length() - 1);
                }
                paraMap.put(MeetRecordEntity.FieldAbsentusercodes, absentUserCodes);
                paraMap.put(MeetRecordEntity.FieldAbsentusernames, absentUserNames);
            }
        }
        // 查询会议类型上级节点
        String meetTypeId = ConvertUtil.convertToString(paraMap.get("meettypeid"));
        List<String> meetTypeList = new ArrayList<>();
        if (meetTypeId.length() > 0) {
            List<MeetTypeManageEntity> parentList = this.meetTypeManageService.queryByWhere("id=" + meetTypeId);
            if (parentList.size() == 1) {
                if (parentList.get(0).getParentid() > 0)
                    meetTypeList.add(ConvertUtil.convertToString(parentList.get(0).getParentid()));
            }
            meetTypeList.add(meetTypeId);
        }
        paraMap.put("selectmeettypelist", meetTypeList);
    }

    /**
     * @param paraMap
     * @return
     * @description:查询已有人员
     * @author: zhanglongfei
     * @date: 2020年11月3日上午9:48:36
     * @modify:
     */
    @GetMapping(value = "/queryList")
    public ResponseResult<Object> queryList(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(" 1=1 ");
            if (paraMap.containsKey("qry_sourcetype")) {
                String value = paraMap.get("qry_sourcetype").toString();
                if (!StringUtil.isEmpty(value))
                    sql.appendSingle(" and sourcetype = '{0}' ", value);
            }
            if (paraMap.containsKey("qry_sourceid")) {
                String value = paraMap.get("qry_sourceid").toString();
                if (!StringUtil.isEmpty(value))
                    sql.appendSingle(" and sourceid = '{0}' ", value);
            }
            List<BasePermissionManageEntity> list = this.basePermissionManageService.queryByWhere(sql.toString());
            // 如果没有发布，则需要查看会议的人员签到记录
            if (ConvertUtil.convertToInt(paraMap.get("state")) != MeetStateEnum.Publish) {
                // 查询会议纪要是否配置了参会人或纪要人员,有一个配置了则不需要修改
                sql.clear();
                sql.appendSingle(" 1=1 ");
                sql.appendSingle(
                        " and sourceid='{0}' and sourcetype='{1}' and (sourceflag = '{2}' or sourceflag='{3}') ",
                        paraMap.get("id"), MeetRecordEntity.tableName, MeetPersonTypeEnum.Attend,
                        MeetPersonTypeEnum.Absent);
                List<BasePermissionManageEntity> permissionList = this.basePermissionManageService
                        .queryByWhere(sql.toString());
                // 没有配置参会人和缺席人则查询操作记录
                if (permissionList.size() == 0) {
                    BasePermissionManageEntity attendEntity = new BasePermissionManageEntity();
                    // 参会人
                    List<Map<String, Object>> yesAttendUserList = this.meetPersonRecordService.queryUserRecord(
                            ConvertUtil.convertToString(paraMap.get("qry_sourceid").toString()),
                            MeetOperateTypeEnum.YesSign);
                    if (yesAttendUserList.size() > 0) {
                        attendEntity.setSourceflag(MeetPersonTypeEnum.Attend);
                        attendEntity.setSourcetype(MeetRecordEntity.tableName);
                        attendEntity.setSourceid(ConvertUtil.convertToString(paraMap.get("qry_sourceid").toString()));
                        attendEntity.setShareobjects(
                                this.getStructData(yesAttendUserList, MeetPersonRecordEntity.FieldUsercode));
                        attendEntity.setShareobjectsdesc(
                                this.getStructData(yesAttendUserList, MeetPersonRecordEntity.FieldUsername));
                        attendEntity.setSharetype(ShareTypeEnum.User);
                        permissionList.add(attendEntity);
                    }
                    // 缺席人
                    BasePermissionManageEntity absendEntity = new BasePermissionManageEntity();
                    List<Map<String, Object>> noAttendUserList = this.meetPersonRecordService.queryUserRecord(
                            ConvertUtil.convertToString(paraMap.get("qry_sourceid").toString()),
                            MeetOperateTypeEnum.NoSign);
                    if (noAttendUserList.size() > 0) {
                        absendEntity.setSourceflag(MeetPersonTypeEnum.Attend);
                        absendEntity.setSourcetype(MeetRecordEntity.tableName);
                        absendEntity.setSourceid(ConvertUtil.convertToString(paraMap.get("qry_sourceid").toString()));
                        absendEntity.setShareobjects(
                                this.getStructData(noAttendUserList, MeetPersonRecordEntity.FieldUsercode));
                        absendEntity.setShareobjectsdesc(
                                this.getStructData(noAttendUserList, MeetPersonRecordEntity.FieldUsername));
                        absendEntity.setSharetype(ShareTypeEnum.User);
                        permissionList.add(absendEntity);
                    }
                }

            }
            return ResponseResult.ok(list);
        } catch (Exception e) {
            return handleControllerException(e);
        }
    }

    /**
     * 结构化数据，逗号分割
     *
     * @return
     * @description:
     * @author: donghang
     * @date: 2020年10月31日下午6:17:29
     * @modify:
     */
    private String getStructData(List<Map<String, Object>> dataList, String filed) {
        String structData = "";
        for (Map<String, Object> map : dataList) {
            structData += map.get(filed) + ",";
        }
        if (structData.length() > 0) {
            structData = structData.substring(0, structData.length() - 1);
        }
        return structData;
    }

    /**
     * 保存数据
     *
     * @param paraMap
     * @return
     * @description:
     * @author: donghang
     * @date: 2020年11月3日下午12:49:47
     * @modify:
     */
    @RequestMapping(value = "/save", method = {RequestMethod.POST, RequestMethod.PUT})
    public ResponseResult<Object> save(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            MeetRecordEntity meetManageEntity = this.service.save(paraMap, this.getUserBean());
            return ResponseResult.ok(meetManageEntity);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * 会议发布
     *
     * @param paraMap
     * @return
     * @description:
     * @author: donghang
     * @date: 2020年11月3日上午8:48:36
     * @modify:
     */
    @Override
    @PostMapping(value = "/publish")
    public ResponseResult<Object> publish(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            // 如果参数包括fromehr，则是人力系统调用，不需要判断会议纪要是否已上传
            if (!paraMap.containsKey("fromehr")) {
                // 判断会议纪要是否已上传，若没上传则返回并提示
                StringBufferProxy whereSql = new StringBufferProxy();
                whereSql.appendSingle(" sourcetype = '{0}' and sourceid = '{1}' and description = 'after' ", AttachmentSourceType, paraMap.get("meetnum"));
                List<CboAttachmentEntity> attachmentList = cboAttachmentService.queryByWhere(whereSql.toString());
                if (attachmentList.size() < 1) {
                    return ResponseResult.error("没有上传会议纪要文件，不能发布！");
                }
            }
            this.service.publish(paraMap, this.getUserBean());
            return ResponseResult.ok("发布成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description: 会议作废
     * @author: donghang
     * @date: 2020年9月1日下午4:22:58
     * @modify:
     */
    @Override
    @PostMapping(value = "/cancel")
    public ResponseResult<Object> cancel(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            this.service.cancel(paraMap, this.getUserBean());
            return ResponseResult.ok("取消发布成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * 通过会议查询会议纪要
     *
     * @param paraMap
     * @description:
     * @author: donghang
     * @date: 2020年11月3日下午10:47:37
     * @modify:
     */
    @GetMapping(value = "/queryRecordByMeet")
    public ResponseResult<Object> queryRecordByMeet(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String sql = this.spellListSql(paraMap);
            List<Map<String, Object>> list = this.service.queryMapByWhere(sql.toString());
            if (list.size() == 0) { // 生成纪要
                MeetManageEntity meetManageEntity = meetManageService
                        .queryById(ConvertUtil.convertToString(paraMap.get("qry_meetid")));
                MeetRecordEntity meetRecordEntity = meetManageService.createRecordByMeet(meetManageEntity, true);
                afterLoad(meetRecordEntity.convertToMap());
                return ResponseResult.ok(meetRecordEntity);
            } else {// 已经生成纪要
                afterLoad(list.get(0));
                return ResponseResult.ok(list.get(0));
            }
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 查询会议记录是否有附件或录音文件
     * @author: chengengwei
     * @date: 2021-04-12
     * @modify:
     */
    @GetMapping(value = "/queryRecordFileStateByIds")
    public ResponseResult<Object> queryRecordFileStateByIds(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            List<Map<String, Object>> resultList = this.service.queryRecordFileStateByIds(paraMap);
            return ResponseResult.ok(resultList);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 设置用户不接收会议纪要消息提醒
     * @author: chengengwei
     * @date: 2021-05-31
     * @modify:
     */
    @PostMapping(value = "/setNotRemindUploadRecord")
    public ResponseResult<Object> setNotRemindUploadRecord(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            this.service.setNotRemindUploadRecord(paraMap, this.getUserBean());
            return ResponseResult.ok("设置不接收消息成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @Description: 根据会议id加载详情
     * @Author: mengmeng
     * @Date: 2021/5/31 15:19
     * @Version: 1.0
     */
    @GetMapping(value = "/loadByMeetId")
    public ResponseResult<Object> loadByMeetId(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String id = ConvertUtil.convertToString(paraMap.get("id"));
            paraMap.put("whereSql", " meetid in (" + id + ")");
            paraMap.put("qry_usercode", this.getUserBean().getUser().getCode());
            List<Map<String, Object>> dataMapList = this.service.queryMap(paraMap, "queryRecordDetail");
            this.service.setDispFields(dataMapList);
            if (dataMapList.size() == 0) {
                return ResponseResult.error("没有查询到会议资料详情数据");
            }
            Map<String, Object> dataMap = dataMapList.get(0);
            afterLoad(dataMap);
            setAccess(paraMap, dataMap);
            return ResponseResult.ok(dataMap);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 将output.m3u8解密，并把http://meetsource.topscomm.net:8967换为https://meetsource.topscomm.com再加密
     * @author: chengengwei
     * @date: 2021-08-11
     * @modify:
     */
    @GetMapping(value = "/dealDecryptDes")
    public ResponseResult<Object> dealDecryptDes(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            byte[] secretContent = FileUtil.readBytes("D:\\output.m3u8");
            String secretKey = ParameterCache.getValue("m3u8SecretKey", "12345678901234567890123456789012");
            byte[] trueContent = SecurityUtil.decryptDes(secretContent, secretKey);
            String trueContentString = new String(trueContent);
            trueContentString = trueContentString.replace("http://meetsource.topscomm.net:8967", "https://meetsource.topscomm.com");
            trueContent = trueContentString.getBytes();
            FileUtil.writeBytes(trueContent, new File("D:\\output_temp.m3u8"), 0, trueContent.length, false);
            secretContent = SecurityUtil.encryptDes(trueContentString.getBytes(), secretKey);
            FileUtil.writeBytes(secretContent, new File("D:\\output_result.m3u8"), 0, secretContent.length, false);
            return ResponseResult.ok("成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 添加附件记录，传参需要所有附件记录
     * @author: chengengwei
     * @date: 2021-08-30
     * @modify:
     */
    @PostMapping(value = "/addAttachmentRecord")
    public ResponseResult<Object> addAttachmentRecord(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            this.service.addAttachmentRecord(paraMap);
            return ResponseResult.ok("上传附件成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @param
     * @return
     * @throws
     * @description:
     * @author xinfushuo
     * @date 2022/8/2
     * @modify
     */
    protected String spellAttachmentListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and name like '%{0}%' ", value);
            }
        }
        if (paraMap.containsKey("qry_enabled")) {
            String value = paraMap.get("qry_enabled").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and enabled = 1 ", value);
            }
        }
        if (paraMap.containsKey("qry_code")) {
            String value = paraMap.get("qry_code").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and code like '%{0}%' ", value);
            }
        }
        if (paraMap.containsKey("qry_sourceType")) {
            String value = paraMap.get("qry_sourceType").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and sourcetype = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("qry_attachmentTypeId")) {
            String value = paraMap.get("qry_attachmentTypeId").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and attachmenttypeid = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("qry_sourceId")) {
            String value = paraMap.get("qry_sourceId").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and sourceid = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("description")) {
            String value = paraMap.get("description").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and description = '{0}' ", value);
            }
        }
        return sql.toString();
    }

    /**
     * @param paraMap
     * @return
     * @description:重写平台查询列表
     * @author:
     * @date:
     * @modify:
     */
    @GetMapping(value = "/queryAttachmentList")
    public ResponseResult<Object> attachmentList(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            BaseUtil.decodeSecureMap(paraMap);
            String sql = this.spellAttachmentListSql(paraMap);
            sql += " order by id";
            List<CboAttachmentEntity> list = cboAttachmentService.queryByWhere(sql);
            return ResponseResult.ok(list);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @param multipartFile 文件
     * @param sourceId
     * @param sourceType
     * @param description
     * @return
     * @throws
     * @author xinfushuo
     * @date 2022/9/5
     * @modify
     */
    @PostMapping(value = "/recordUpload")
    public ResponseResult<Object> cboAttachmentUpload(@RequestParam("file") MultipartFile multipartFile, @RequestParam String sourceId, @RequestParam String sourceType, @RequestParam String description) {
        File file = null;
        try {
            String filename = multipartFile.getOriginalFilename();
            file = new File(filename);
            Map<String, Object> paraMap = new HashMap<>();
            paraMap.put("sourceType", sourceType);
            paraMap.put("sourceId", sourceId);
            paraMap.put("description", description);
            Map<String, Object> map;
            beforeUpload(sourceType, sourceId, description);
            //此处需要指定路径 否则会声称在其他目录下 导致FileNotFoundException
            multipartFile.transferTo(file.getAbsoluteFile());
            map = cboAttachmentService.executeUpload(paraMap, file);
            return ResponseResult.ok(map);
        } catch (IOException e) {
            e.printStackTrace();
            log.warn(e.getMessage());
            return ResponseResult.error(TapHttpStatus.HTTP_OK, TapHttpErrorCode.SUCCESS, "转换文件失败");
        }finally {
            boolean deleted = FileUtil.del(file);
            if(!deleted){
                log.warn("文件没有被正确删除");
            }
        }
    }

    /**
     * 上传附件之前进行判断  销售项目会议需停止签到之后才能上传会议
     *
     * @param sourceId
     * @param sourceType
     * @param description
     * @author xinfushuo
     * @date 2022/9/5
     * @modify
     */
    private void beforeUpload(String sourceType, String sourceId, String description) {
        if(StrUtil.isEmpty(sourceId)||StrUtil.isEmpty(sourceType)){
            throw new ServiceException("缺少来源标识参数！,请联系系统管理员");
        }
        if(!sourceType.contentEquals(MeetSystemConst.MeetAttachMentSourceTypeEnum.MeetRecord)){
            return;
        }
        if(StrUtil.isEmpty(description)){
            throw new ServiceException("缺少会议标识参数！,请联系系统管理员");
        }
        //会前资料不控制
        if("before".contentEquals(description)){
            return;
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" {0} = '{1}' ", MeetManageEntity.FieldMeetnum, sourceId);
        MeetManageEntity meetManage = meetManageService.queryObjectByWhere(sql.toString());
        //会议找不到的不控制  此时有两种情况 一为会议纪要 补录 二为对应会议被删除（应该不会出现，两者删除是同步的）
        if (meetManage == null) {
           return;
        }
        //只有当会议为销售项目会议时
        if (meetManage.getSourceapp()!=null&&MeetSystemConst.MeetSourceAppEnum.MPM.contentEquals(meetManage.getSourceapp())) {
            if (meetManage.getSignstate() == BaseSystemConst.CboYesNoEnum.Yes) {
                throw new ServiceException("该会议尚未结束签到，无法上传会议纪要。");
            }
        }
    }
}
